﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.LinqBuilder;
using Microsoft.EntityFrameworkCore;
using Queer.AutoJob.Core.Entity;
using Queer.AutoJob.Core.Model;
using Queer.Util;
using Queer.Util.Helper;
using Queer.Util.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Queer.AutoJob.Core.Service
{
    /// <summary>
    /// 创 建：
    /// 日 期：2021-04-01 09:15
    /// 描 述：定时任务服务类
    /// </summary>

    public class AutoJobService : IAutoJobService, ITransient
    {
        private readonly IRepository<AutoJobEntity> _autoJobDB;

        public AutoJobService(IRepository<AutoJobEntity> autoJobDB)
        {
            _autoJobDB = autoJobDB;
        }

        #region 获取数据

        /// <summary>
        /// 带条件查询所有
        /// </summary>
        public async Task<List<AutoJobEntity>> GetList(AutoJobListParam param)
        {
            IQueryable<AutoJobEntity> query = ListFilter(param);
            var data = await query.ToListAsync();
            return data;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<List<AutoJobEntity>> GetPageList(AutoJobListParam param, Pagination pagination)
        {
            IQueryable<AutoJobEntity> query = ListFilter(param);
            var data = await query.OrderByDescending(a => a.Id).ToPagedListAsync(pagination.PageIndex, pagination.PageSize);

            // 分页参数赋值
            pagination.TotalCount = data.TotalCount;
            return data.Items.ToList();
        }

        /// <summary>
        /// 根据ID获取对象
        /// </summary>
        public async Task<AutoJobEntity> GetEntity(long id)
        {
            var data = await _autoJobDB.AsQueryable(p => p.Id == id).FirstOrDefaultAsync();
            return data;
        }

        /// <summary>
        /// 查询多个ID主键数据
        /// </summary>
        public async Task<List<AutoJobEntity>> GetListByIds(string ids)
        {
            if (ids.IsNullOrEmpty())
                throw new Exception("参数不合法！");

            var idArr = TextHelper.SplitToArray<long>(ids, ',').ToList();
            var data = await _autoJobDB.AsQueryable(a => idArr.Contains(a.Id.GetValueOrDefault())).ToListAsync();

            return data;
        }

        #endregion

        #region 提交数据

        public async Task SaveForm(AutoJobEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                // 默认赋值
                entity.Id = IdGeneratorHelper.Instance.GetId();
                await _autoJobDB.InsertNowAsync(entity);
            }
            else
            {
                await _autoJobDB.UpdateNowAsync(entity, true);
            }
        }

        public async Task DeleteForm(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids))
                throw new Exception("参数不合法！");

            var _ids = ids.Split(",");
            await _autoJobDB.BatchFakeDeleteAsync(_ids);
        }

        #endregion

        #region 私有方法
        private IQueryable<AutoJobEntity> ListFilter(AutoJobListParam param)
        {
            IQueryable<AutoJobEntity> query = _autoJobDB.AsQueryable();
            if (param != null)
            {
                // 任务组名称
                if (!string.IsNullOrEmpty(param.JobGroupName))
                    query = query.Where(p => p.JobGroupName.Contains(param.JobGroupName));
                // 任务名称
                if (!string.IsNullOrEmpty(param.JobName))
                    query = query.Where(p => p.JobName.Contains(param.JobName));
                // 任务状态(0禁用 1启用)
                if (param.JobStatus.HasValue)
                    query = query.Where(p => p.JobStatus == param.JobStatus);
                // cron表达式
                if (!string.IsNullOrEmpty(param.CronExpression))
                    query = query.Where(p => p.CronExpression.Contains(param.CronExpression));
                // 运行开始时间
                if (param.StartTime.HasValue)
                    query = query.Where(p => p.StartTime == param.StartTime);
                // 运行结束时间
                if (param.EndTime.HasValue)
                    query = query.Where(p => p.EndTime == param.EndTime);
                // 下次执行时间
                if (param.NextStartTime.HasValue)
                    query = query.Where(p => p.NextStartTime == param.NextStartTime);
                // 备注
                if (!string.IsNullOrEmpty(param.Remark))
                    query = query.Where(p => p.Remark.Contains(param.Remark));

            }

            query = query.Where(a => a.IsDelete != true);

            return query;
        }

        #endregion
    }
}